 
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use crate::core::manifest::{ContributeDefinition, ContributionPointDefinition};
use crate::core::services::context::ActivateContext;
use crate::core::services::contribution_keyword_manager::IContributionKeyword;
use super::types::ICommandHandler;


/// 命令系统的核心实现，负责管理所有命令处理器
pub struct CommandsImplement {
    handlers: Arc<Mutex<HashMap<String, Box<dyn ICommandHandler>>>>,
}

impl CommandsImplement {
    pub fn new() -> Self {
        Self { handlers: Arc::new(Mutex::new(HashMap::new())) }
    }

    pub fn register(&self, command_name: &str, handler: Box<dyn ICommandHandler>) {
        self.handlers.lock().unwrap().insert(command_name.to_string(), handler);
    }

    pub fn execute(&self, command_name: &str, args: Arc<dyn std::any::Any + Send + Sync>) -> Result<Arc<dyn std::any::Any + Send + Sync>, String> {
        let handlers = self.handlers.lock().unwrap();
        if let Some(handler) = handlers.get(command_name) {
            handler.execute(args)
        } else {
            Err(format!("Command '{}' not found", command_name))
        }
    }
}

impl IContributionKeyword for CommandsImplement {
    /// 当有插件向 `commands` 关键字贡献时，此方法被调用
    fn request_contribution(&self, _ctx: &ActivateContext, definitions: &[ContributeDefinition]) {
        // 在我们的设计中，命令的注册是动态的，通过调用 ctx.commands.register() 完成。
        // 所以这里只是打印日志，表示我们收到了贡献声明。
        for def in definitions {
            println!("CommandsImplement: Received contribution declaration '{}' from plugin '{}'", def.name, _ctx.contributor);
        }
    }

    fn request_contribution_point(&self, _ctx: &ActivateContext, _definitions: &[ContributionPointDefinition]) {
        // `commands` 插件不支持其他插件向它贡献“贡献点”
    }
}
